package com.henrybit.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.torque.Torque;

import com.henrybit.exception.DBException;

/**
 * 数据库初始化<br>
 * @author henrybit
 * @version 1.0
 */
public class DBFactory {
	
	/**
	 * 注册数据库 驱动<p>
	 * @throws DBException
	 */
	public static void init() throws DBException {
		try {
			Class.forName(Constant.DB_DRIVER_CLASS);		
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			throw new DBException(e, Constant.DB_INIT_DRIVER_CLASS_NOTFOUND, "注册DB驱动失败：未找到驱动类");
		} catch (Exception e) {
			throw new DBException(e, Constant.DB_INIT_DRIVER_ERROR, "注册DB驱动失败");
		}
	}
	
	/**
	 * 返回一个数据库连接<p>
	 * @return java.sql.Connection
	 * @throws DBException
	 */
	public static Connection getConnection() throws DBException {
		Connection con = null;
		try {
			con = DriverManager.getConnection(Constant.DB_URL, Constant.DB_USER, Constant.DB_PASSWD);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new DBException(e,Constant.DB_GET_CONNECTION_ACCESS_DB_FAILED, "DB访问失败");
		} catch (Exception e) {
			throw new DBException(e, Constant.DB_GET_CONNECTION_ERROR,"未知");
		}
		return con;
	}
	
	/**
	 * @deprecated
	 * 初始化数据库连接<br>
	 * @param config
	 * @throws Exception
	 */
	public static void init(String config) throws DBException {
		try {
			Torque.init(config);
		} catch(Throwable e) {
			throw new DBException(e);
		}
	}
	
	/**
	 * @deprecated
	 * 释放数据库连接<br>
	 * @throws DBException
	 */
	public static void destroy() throws DBException {
		try {
			Torque.shutdown();
		} catch(Throwable e) {
			throw new DBException(e);
		}
	}
}
